﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CloudReader.Server.Runtime;

namespace CloudReader.Server
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : System.Windows.Window
    {
        System.Timers.Timer Delay;
        ServerRuntime runtime;
        public MainWindow()
        {
            InitializeComponent();
            Delay = new System.Timers.Timer(1000);
            runtime = DataContext as ServerRuntime;
            Delay.Elapsed += (o, e) =>
            {
                Dispatcher.Invoke(() =>
                {
                    CurrentAvaliable.Text = ServerRuntime.CurrentAvaliableConnection.ToString();
                    CurrentConnection.Text = ServerRuntime.CurrentConnection.ToString();
                    UsedMemory.Text = ServerRuntime.UsedMemory.ToString();
                    CurrentExecuteFrame.Text = ServerRuntime.CurrentExecuteFrame.ToString();
                    CurrentAvaliableChart.EndAngle = (ServerRuntime.CurrentAvaliableConnection / ServerRuntime.TotalAvaliableConnection) * 360d;
                    CurrentConnectionChart.EndAngle = (ServerRuntime.CurrentConnection / ServerRuntime.MaxConnection) * 360d;
                    UsedMemoryChart.EndAngle = (ServerRuntime.UsedMemory / ServerRuntime.TotalMemory) * 360d;
                    CurrentExecuteFrameChart.EndAngle = (ServerRuntime.CurrentExecuteFrame / ServerRuntime.MaxExecuteFrame) * 360d;
                    if(Event.Items.Count>1024)
                    {
                        Event.Items.Clear();
                    }
                    if(ExceptionPool1.Items.Count>128)
                    {
                        ExceptionPool1.Items.Clear();
                    }
                    try
                    {
                        lock (runtime.Event)
                        {
                            while (runtime.Event.Count > 0)
                            {
                                Event.Items.Add(runtime.Event.Dequeue());
                            }
                        }
                        lock (runtime.Event)
                        {
                            while (runtime.ExceptionPool.Count > 0)
                            {
                                ExceptionPool1.Items.Add(runtime.ExceptionPool.Dequeue());
                            }
                        }
                    }
                    catch(InvalidOperationException ex)
                    {
                        throw ex;
                    }
                });
            };
            Delay.Start();
        }
    }
}
